#!/bin/sh /etc/rc.common

START=99
CONFIG=timecontrol

uci_get_by_type() {
	local index=0
	[ -n $4 ] && index=$4
	local ret=$(uci -q get $CONFIG.@$1[$index].$2 2>/dev/null)
	echo ${ret:=$3}
}

add_rule(){

	rulessum=$(grep -c 'macbind' /etc/config/$CONFIG)

	for i in $(seq 0 $((rulessum-1)))
	do
		enable=$(uci get $CONFIG.@macbind[$i].enable 2>/dev/null)
		if [ "$enable" == 1 ]; then
 			macaddr=$(uci get $CONFIG.@macbind[$i].macaddr 2>/dev/null) && MAC="-m mac --mac-source $macaddr" || MAC=""
 			timestart=$(uci get $CONFIG.@macbind[$i].timeon 2>/dev/null) || timestart="00:00"
 			timestop=$(uci get $CONFIG.@macbind[$i].timeoff 2>/dev/null) ||  timestop="00:00"
 			week_days=$(uci get $CONFIG.@macbind[$i].daysofweek |sed 's/ /,/g' 2>/dev/null)
 			[ "$timestart" = "$timestop" ] && TIME="" || TIME="--timestart ${timestart} --timestop ${timestop}"
			 [ -z "$week_days" -o "$week_days" = "Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday" ] && WEEK="" || WEEK="--weekdays ${week_days}"
 			[ -n "$TIME" -o -n "$WEEK" ] && TME="-m time --kerneltz ${TIME} ${WEEK}" || TME=""
				iptables -t filter -I TIMECONTROL  ${MAC} ${TME}  -j DROP
				ip6tables -t filter -I TIMECONTROL  ${MAC} ${TME}  -j DROP
				iptables -t nat -I PREROUTING 1  ${MAC} ${TME}  -m comment --comment "TIMECONTROL" -j RETURN
				ip6tables -t nat -I PREROUTING 1  ${MAC} ${TME}  -m comment --comment "TIMECONTROL" -j RETURN
		fi
	done
echo "/etc/init.d/timecontrol restart" > "/var/etc/timecontrol.include"
}

del_rule(){
	nums=$(iptables -t nat -n -L PREROUTING 2>/dev/null | grep -c "TIMECONTROL")
	if [ -n "$nums" ]; then
		until [ "$nums" = 0 ]
		do
			rules=$(iptables -t nat -n -L PREROUTING --line-num 2>/dev/null | grep "TIMECONTROL" | awk '{print $1}')
			rules6=$(ip6tables -t nat -n -L PREROUTING --line-num 2>/dev/null | grep "TIMECONTROL" | awk '{print $1}')
			for rule in $rules
			do
				iptables -t nat -D PREROUTING $rule 2>/dev/null
				ip6tables -t nat -D PREROUTING $rule 2>/dev/null
				break
			done
			nums=$(expr $nums - 1)
		done
	fi
}

start(){
	ENABLED=$(uci_get_by_type basic enable 0)
	[ "$ENABLED" != "1" ] && exit 0
	iptables -t filter -N TIMECONTROL
	ip6tables -t filter -N TIMECONTROL
	iptables -t filter -I FORWARD -j TIMECONTROL
	ip6tables -t filter -I FORWARD -j TIMECONTROL
	add_rule
}

stop(){
	iptables -t filter -D FORWARD -j TIMECONTROL 2>/dev/null
	iptables -t filter -F TIMECONTROL 2>/dev/null
	iptables -t filter -X TIMECONTROL 2>/dev/null
	ip6tables -t filter -D FORWARD -j TIMECONTROL 2>/dev/null
	ip6tables -t filter -F TIMECONTROL 2>/dev/null
	ip6tables -t filter -X TIMECONTROL 2>/dev/null
	del_rule
}
